package com.aya.client;

import com.aya.modules.friend.FriendCodes;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.*;

public class SimpleChatClient {
    public static void main(String[] args) throws Exception {
        new SimpleChatClient("localhost", 8080).run();
    }

    private final String host;
    private final int port;

    public SimpleChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new SimpleChatClientInitializer());
            Channel channel = bootstrap.connect(host, port).sync().channel();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = in.readLine();
                switch (msg) {
                    case "login":
                        writeLogin(channel, FriendCodes.LOGIN_REQ);
                        break;
                    case "friend":
                        writeFriend(channel);
                        break;
                    default:
                        System.out.println(msg);
                        break;
                }
                channel.writeAndFlush(msg.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

    private void writeFriend(Channel channel) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(byteArrayOutputStream);
        out.writeShort(FriendCodes.FRIEND_LIST);
        byteArrayOutputStream.write("我的好友列表".getBytes());
        channel.writeAndFlush(byteArrayOutputStream.toByteArray());
    }

    private void writeLogin(Channel channel, int loginReq) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(byteArrayOutputStream);
        out.writeShort(loginReq);
        out.write("zs/123".getBytes());
        channel.writeAndFlush(byteArrayOutputStream.toByteArray());
    }
}


